package com.example.demo.rabbitmq;

import com.rabbitmq.client.Channel;
import org.springframework.amqp.core.ExchangeTypes;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.*;
import org.springframework.stereotype.Component;

import java.io.IOException;

/**
 * @Author: HouZeYu
 * @Description:
 * @Date: Created in 16:45 2019/8/7
 */
@Component
public class ListenerMessage {

   @RabbitListener(bindings = {@QueueBinding(value =
    @Queue(value = "zymall.test.queue",durable = "true",autoDelete = "false"),exchange = @Exchange(type = ExchangeTypes.TOPIC,value = "zymall.mq.exchange"),key = "mq.ceshi")})
    public void getDirectMessage(Channel channel, Message message) throws IOException {
        try {
            int a=1/0;
            // 确认收到消息，false只确认当前consumer一个消息收到，true确认所有consumer获得的消息
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
        } catch (Exception e) {
            if (message.getMessageProperties().getRedelivered()) {
                System.out.println("消息已重复处理失败,拒绝再次接收" );
                // 拒绝消息，requeue=false 表示不再重新入队，如果配置了死信队列则进入死信队列
                channel.basicReject(message.getMessageProperties().getDeliveryTag(), false);
            } else {
                System.out.println("消息即将再次返回队列处理" );
                // requeue为是否重新回到队列，true重新入队
                channel.basicNack(message.getMessageProperties().getDeliveryTag(), false, true);
            }
            //e.printStackTrace();
        }
    }


    @RabbitHandler
    @RabbitListener(queues = "topicC")
    public void receive(Message message, Channel channel) throws IOException {
        try {
            channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
            System.out.println("接受到的消息为"+new String(message.getBody(),"UTF-8"));
        } catch (Exception e) {
            channel.basicNack(message.getMessageProperties().getDeliveryTag(),false,true);
        }
    }
}
